package com.dede.baselib

import android.content.Context
import android.graphics.Color
import android.support.annotation.IdRes
import android.support.annotation.LayoutRes
import android.support.v4.view.PagerAdapter
import android.support.v4.view.ViewPager
import android.support.v7.widget.GridLayoutManager
import android.support.v7.widget.RecyclerView
import android.util.AttributeSet
import android.util.SparseArray
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.FrameLayout
import android.widget.TextView

/**
 * 分页显示的列表
 * Created by hsh on 2018/2/28.
 */
class PagerList<T> : FrameLayout {

    constructor(context: Context) : this(context, null)
    constructor(context: Context, attrs: AttributeSet?) : this(context, attrs, 0)
    constructor(context: Context, attrs: AttributeSet?, defStyleAttr: Int) : super(context, attrs, defStyleAttr)

    private var lines: Int = 2// 行
    private var columns: Int = 4// 列

    private var datas: List<T>? = null
    private var bindViewData: ((T, Holder) -> Unit)? = null
    @LayoutRes
    private var itemLayout = -1

    private val viewPager: ViewPager

    init {
        viewPager = WrapContentHeightViewPager(context)
    }

    fun lines(lines: Int): PagerList<T> {
        this.lines = lines
        return this
    }

    fun columns(columns: Int): PagerList<T> {
        this.columns = columns
        return this
    }

    fun data(datas: List<T>): PagerList<T> {
        this.datas = datas
        return this
    }

    fun bindViewData(bindViewData: (T, Holder) -> Unit): PagerList<T> {
        this.bindViewData = bindViewData
        return this
    }

    fun layout(@LayoutRes layoutId: Int): PagerList<T> {
        this.itemLayout = layoutId
        return this
    }

    fun finish() {
        viewPager.adapter = InnerPagerAdapter()
        addView(viewPager)
    }

    fun getViewPager(): ViewPager {
        return viewPager
    }


    inner class InnerPagerAdapter : PagerAdapter() {

        override fun isViewFromObject(view: View?, `object`: Any?) = view == `object`

        override fun getCount() = if (datas == null) 0 else {
            val size = datas!!.size
            val pagerChildCount = lines * columns
            if (size % pagerChildCount > 0)
                size / pagerChildCount + 1
            else
                size / pagerChildCount
        }

        override fun instantiateItem(container: ViewGroup?, position: Int): Any {
            val view = RecyclerView(context)
            val pagerChildCount = lines * columns
            val childDatas: List<T> = if (datas != null) {
                val startIndex = pagerChildCount * position
                val endIndex = pagerChildCount * (position + 1)
                if (endIndex > datas!!.size) {
                    datas!!.subList(startIndex, datas!!.size)
                } else {
                    datas!!.subList(startIndex, endIndex)
                }
            } else {
                emptyList()
            }
            if (itemLayout != -1 && bindViewData != null) {
                view.adapter = InnerListAdapter(childDatas)
            }
            val layoutManager = object : GridLayoutManager(context, columns) {
                override fun canScrollVertically() = false
            }
            view.layoutManager = layoutManager
            view.setBackgroundColor(Color.RED)
            view.layoutParams = ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT)

            container?.addView(view)
            return view
        }

        override fun destroyItem(container: ViewGroup?, position: Int, `object`: Any?) {
            container?.removeView(`object` as View)
        }
    }

    /**
     * RecyclerView适配器
     */
    private inner class InnerListAdapter(val datas: List<T>) : RecyclerView.Adapter<Holder>() {

        override fun onCreateViewHolder(parent: ViewGroup?, viewType: Int): Holder {
            val view = LayoutInflater.from(context).inflate(itemLayout, parent, false)
            return Holder(view)
        }

        override fun onBindViewHolder(holder: Holder?, position: Int) {
            if (bindViewData != null && datas.isNotEmpty()) {
                bindViewData!!.invoke(this.datas[position], holder!!)
            }
        }

        override fun getItemCount() = datas.size
    }

    class Holder(view: View) : RecyclerView.ViewHolder(view) {

        private val views: SparseArray<View> = SparseArray()

        fun <T : View> getView(@IdRes id: Int): T {
            var t = views[id]
            if (t == null) {
                t = itemView.findViewById(id)
                views.put(id, itemView)
            }
            return t as T
        }

        fun setText(@IdRes id: Int, text: CharSequence): Holder {
            val view = getView<TextView>(id)
            view.text = text
            return this
        }

        //todo add other set function
    }


    /**
     * 高度自适应的ViewPager
     */
    class WrapContentHeightViewPager : ViewPager {

        constructor(context: Context) : super(context)

        constructor(context: Context, attrs: AttributeSet) : super(context, attrs)

        override fun onMeasure(widthMeasureSpec: Int, heightMeasureSpec: Int) {
            var heightMeasureSpecCopy = heightMeasureSpec

            var height = 0
            for (i in 0 until childCount) {
                val child = getChildAt(i)
                child.measure(widthMeasureSpec, View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED))
                val h = child.measuredHeight
                if (h > height) height = h
            }

            if (height != 0) {
                heightMeasureSpecCopy = View.MeasureSpec.makeMeasureSpec(height, View.MeasureSpec.EXACTLY)
            }

            super.onMeasure(widthMeasureSpec, heightMeasureSpecCopy)
        }

    }
}